<?php

require_once __DIR__.'/../config.php';
require_once __DIR__.'/sql.php';
require_once __DIR__.'/class_aes.php';

function token_get($username){
    $token = md5($username.time().rand()); 
    $time = time() + 604800;

    $sql_link = MySQL::getInstance();
    $res = $sql_link->prepare('UPDATE users SET token = :user_token WHERE username = :username');
    $res->bindParam(':username',$username);
    $res->bindParam(':user_token',$user_token);
    $user_token = $time.'|'.$token;
    $res->execute();

    $res = $sql_link->prepare('SELECT id FROM users WHERE username = :username');
    $res->bindParam(':username',$username);
    $res->execute();
    $data = $res->fetch(PDO::FETCH_ASSOC);

    $id = $data['id'];
    $token = $id.'|'.$token;
    $token = AES::encrypt($token,TOKEN_KEY);

    return $token;
}

function token_verify($token){

    $token = AES::decrypt($token,TOKEN_KEY);
    $temp = explode('|',$token,2);
    $id = $temp[0];
    $token = $temp[1];

    $sql_link = MySQL::getInstance();
    $res = $sql_link->prepare('SELECT token,identity FROM users WHERE id = :id');
    $res->bindParam(':id',$id);
    $res->execute();
    $data = $res->fetch(PDO::FETCH_ASSOC);

    $user_token = $data['token'];
    $temp = explode('|',$user_token,2);
    $time_save = $temp[0];
    $token_save = $temp[1];
    $time = time();

    if($time < $time_save && $token_save == $token){
        //更新过期时间
        $time = $time + 604800;
        $res = $sql_link->prepare('UPDATE users SET token = :user_token WHERE id = :id');
        $res->bindParam(':id',$id);
        $res->bindParam(':user_token',$user_token);
        $user_token = $time.'|'.$token_save;
        $res->execute();
        unset($data['token']);
        $data['id'] = $id;
        return $data;
    }
    return '';
}